<script setup>
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import { useCartStore } from '@/stores/cart';
import { useUserStore } from '@/stores/user';
import { insertCart, subCartNum, delOne, clearCart, checkOne, unCheckOne, checkAll, unCheckAll,submitCart } from '@/api/cart';
import { computed, ref, watch } from 'vue';

const router = useRouter()

let timer = undefined
async function changeNUm(sign, item) {
    if (timer) return
    if (sign === '+') {
        const res = await insertCart({ goodsId: item.goodsId, goodsSpecsId: item.goodsSpecsId })
        if (res.code === 0) {
            alert(res.msg)
            return
        }
    } else {
        if (item.goodsNumber <= 1) return
        await subCartNum({ goodsId: item.goodsId, goodsSpecsId: item.goodsSpecsId })
    }
    useCartStore().getCartList()
    timer = setTimeout(() => {
        clearTimeout(timer)
        timer = undefined
    }, 1000)
}

async function delCart(flag, id) {
    let res = confirm('确定要删除商品吗亲亲')
    if (!res) return
    if (flag) {
        //代表全清
        await clearCart()
    } else {
        //清楚单个
        await delOne(id)
    }
    useCartStore().getCartList()

}
const totalPrice = computed(() => {
    return useCartStore().cartList?.reduce((pre, now) => {
        if(now.isChecked){
             pre += now.goodsNumber * now.goodsPrice
        }
        return pre
    }, 0)
})
// 用户选择的收货地址id
const { addrList } = storeToRefs(useUserStore())
const defaultAddrId = ref(undefined)
watch(addrList, (n, o) => {
    if (n && n.length > 0) {
        addrList.value.some(it => {
            if (it.isDefault === 1) {
                defaultAddrId.value = it.id
            }
        })
    }
}, { immediate: true })

//结算
async function goSettlement() {
  
  
    const { data } = await submitCart(
        defaultAddrId.value
    )
    
    router.replace(`/order?id=${data.id}&address=${data.address}&name=${data.consignee}&time=${data.orderTime}&phone=${data.phone}&amount=${totalPrice.value.toFixed(2)}&status=${data.status}&estimatedDeliveryTime=${data.estimatedDeliveryTime}`)
}

//选中操作

const isCheckAll = computed({
    get(){
        return  !useCartStore().cartList.some(it => it.isChecked === false)
    },
   async set(val){
        if(val){
            await checkAll()
        }else{
            await unCheckAll()
        }
    useCartStore().getCartList()

    }
})
async function doCheck(e,id){
    if(e){
        await checkOne(id)
    }else{
        await unCheckOne(id)
    }
}

</script>

<template>
    <div class="cart">
        <h1>
            <img src="/public/logo.png" alt="" style="float: left; width: 100px;">
            我的购物车
            <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-gouwuche1"></use>
            </svg>
        </h1>
        <div class="main">
            <div class="content">
                <table>

                    <template v-if="useCartStore().cartList.length > 0">
                        <thead style=" height: 50px; border-bottom: 1px solid #e0e0e0;">
                            <tr align="left">
                                <th>
                                    <el-checkbox v-model="isCheckAll" size="large" style="vertical-align: middle;"/>
                                    全/反选
                                </th>
                                <th style="width: 25%;">商品名称</th>
                                <th>商品图片</th>
                                <th>商品价格</th>
                                <th>商品数量</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(item, index) in useCartStore().cartList" :key="item.id">
                                <td>
                                    <el-checkbox v-model="item.isChecked " size="large" style="vertical-align: middle;" @change="(e) => doCheck(e,item.id)" />
                                </td>
                                <td style="width: 25%;">
                                    {{ item.goodsName }}
                                    <p style="color: #b0a3a3;font-size: 12px;">{{ item.goodsSpecsName }}</p>
                                </td>
                                <td style="padding-top: 10px;">
                                    <!-- <img src="" alt=""> -->
                                    <img :src="item.goodsImage" alt="">
                                </td>
                                <td>
                                    ￥<span>{{ item.goodsPrice.toFixed(2) }}</span>
                                </td>
                                <td>
                                    <div class="count">
                                        <button @click="changeNUm('-', item)">-</button>
                                        {{ item.goodsNumber }}
                                        <button @click="changeNUm('+', item)">+</button>
                                    </div>
                                </td>
                                <td>
                                    <button style="font-size: 18px; width: 30px; height: 30px;"
                                        @click="delCart(false, item.id)">×</button>
                                </td>
                            </tr>
                        </tbody>
                    </template>
                    <div v-else class="empty">
                        购物车空空如也
                    </div>
                </table>

                <div class="address_book" v-if="useCartStore().cartList.length > 0">
                    <div class="addr_top">
                        <div class="item" :class="{ active: it.id === defaultAddrId }" v-for="it in addrList"
                            :key="it.id" @click="defaultAddrId = it.id">
                            <h2>{{ it.consignee }}</h2>
                            <span>{{ it.phone }}</span>
                            <p>{{ `${it.provinceName} ${it.cityName} ${it.districtName}` }}</p>
                            <p>{{ it.detail }}</p>
                        </div>
                    </div>
                    <router-link to="/my">去修改地址</router-link>

                </div>

                <div class="settlement" v-show="useCartStore().cartList.length > 0">
                    <div class="left">
                        <router-link to="/home">继续购物</router-link>
                        <span>|</span>
                        <button @click="delCart(true)">清空购物车</button>
                        <div class="total">
                            合计：<span>{{ totalPrice }}</span> 元
                        </div>
                    </div>
                    <button class="right" @click="goSettlement">去结算</button>
                </div>
            </div>
        </div>

    </div>
</template>

<style scoped lang="less">
.main {
    background-color: #fafafa;

    .address_book {
        height: 200px;
        transform: translateY(6%);
        color: #757575;

        .addr_top {
            height: 178px;

            .active {
                border: 1px solid #1697d9 !important;
                background-color: #fff;
            }

            .item {
                float: left;
                text-align: center;
                display: flex;
                flex-direction: column;
                justify-content: center;
                cursor: pointer;
                margin-right: 22px;
                width: 290px;
                height: 178px;
                border: 1px solid #e0e0e0;
                transition: all .3s;

                &:nth-of-type(4) {
                    margin-right: 0;
                }

                &:hover {
                    border-color: #b0b0b0;
                }

                &:nth-of-type(1):hover .desc i {
                    // border-color: #b0b0b0;
                    color: black;
                }
            }
        }

        a {
            display: block;
            transform: translateY(17%);
            color: #757575;
        }


    }

    .empty {
        font-size: 20px;
        color: #a19797;
        text-align: center;
        line-height: 500px;
    }

    .settlement {
        margin-top: 20px;
        height: 50px;
        background-color: #fff;

        .left {
            float: left;
            width: 80%;
            padding: 10px 0;
            height: 100%;

            .total {
                float: right;
                color: #4ab4eb;

                width: 150px;
                height: 100%;
                line-height: 30px;

                span {
                    font-size: 20px;
                    color: #1697d9;

                }
            }

            button,
            a {
                width: 100px;
                height: 100%;
                color: #757575 !important;
            }

            span {
                color: #eeeeee;

            }

            a {
                float: left;
                line-height: 30px;
                text-align: center;
                display: inline-block;
            }
        }

        .right {
            float: right;
            width: 20%;
            height: 100%;
            background-color: #4ab4eb;
            color: #fff;
            font-size: 18px;
        }
    }

    table {
        width: 100%;
        min-height: 500px;
        border-collapse: collapse;
        background-color: #fff;

        th,
        td {
            width: 15%;
        }



        img {
            width: 100px;
            height: 100px;
        }

        .count {
            text-align: center;
            line-height: 50px;
            width: 120px;
            height: 50px;
            border: 1px solid #e0e0e0;

            button {
                font-size: 18px;
                height: 100%;
                width: 40%;
            }

            :nth-child(1) {
                float: left;
            }

            :nth-child(2) {
                float: right;

            }
        }
    }
}


h1 {
    text-align: center;
    height: 106px;
    line-height: 106px;
    font-weight: 400;
    border-bottom: 1px solid #5ebced;
}

.icon {
    width: 2em;
    height: 2em;
    vertical-align: middle;
    fill: currentColor;
    overflow: hidden;
}
</style>
